package com.offcn.user.controller;

import com.mysql.cj.util.TimeUtil;
import com.offcn.dycommon.response.AppResponse;
import com.offcn.user.service.UserService;
import com.offcn.user.component.SmsTemplate;
import com.offcn.user.pojo.TMember;
import com.offcn.user.vo.req.UserRegistVo;
import com.offcn.user.vo.req.UserRespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.coyote.OutputBuffer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Auther:Justc
 * @Date:2021/5/12 21:34
 * @Description
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户登录/注册模块 (包括忘记密码等)")
@Slf4j
public class UserLoginController {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserService userService;


    /**
     * 根据用户编号获取用户信息
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id查询")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "用户id", required = true)
    })
    @GetMapping("/findUser/{id}")
    public AppResponse<UserRegistVo> findUser(@PathVariable("id") Integer id) {

        TMember member = userService.findTmemberById(id);
        UserRegistVo userRegistVo = new UserRegistVo();
        BeanUtils.copyProperties(member, userRegistVo);
        return AppResponse.ok(userRegistVo);
    }




    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @ApiOperation("用户登录")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })

    @PostMapping("/login")
    public AppResponse<UserRespVo> login(String username, String password) {
        //1.尝试登录
        TMember member = userService.login(username, password);
        if (member == null) {
            //登录失败
            AppResponse<UserRespVo> fail = AppResponse.fail(null);
            fail.setMsg("用户名或密码错误");
            return fail;
        }

        //2. 登陆成功:生成令牌
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        UserRespVo userRespVo = new UserRespVo();
        BeanUtils.copyProperties(member, userRespVo);
        userRespVo.setAccessToken(token);

        //3.经常根据令牌查询用户的id,修改redis中用户数据
        redisTemplate.opsForValue().set(token,member.getId()+"",200, TimeUnit.HOURS);
        return AppResponse.ok(userRespVo);
    }




    /**
     * 注册用户
     * @param registerVo
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("register")
    public AppResponse<Object> regist(UserRegistVo registerVo) {
        //1. 检验短信验证码
        String code = redisTemplate.opsForValue().get(registerVo.getLoginacct());
        if (!StringUtils.isEmpty(code)) { //判断code是否为空
            //redis中有验证码
            boolean b = code.equalsIgnoreCase(registerVo.getCode());//忽略大小写
            if (b) {
                //2. 将封装类型转换成数据对象
                TMember member = new TMember();
                BeanUtils.copyProperties(registerVo, member);
                try {
                    userService.registerUser(member);
                    log.debug("用户信息注册成功:{}", member.getLoginacct());
                    //4. 注册成功后删除验证码
                    redisTemplate.delete(registerVo.getLoginacct());
                    return AppResponse.ok("注册成功啦");
                } catch (Exception e) {
                    return AppResponse.fail(e.getMessage());
                }
            } else { //验证码不正确
                return AppResponse.fail("验证码错误");
            }

        } else {
            return AppResponse.fail("验证码过期了,请重新发送");
        }


    }


    /**
     * 获取注册短信验证码
     * @param phoneNo
     * @return
     */
    @ApiOperation("获取注册短信验证码")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phoneNo", value = "手机号", required = true)
    })//@ApiImplicitParams：描述所有参数；@ApiImplicitParam描述某个参数

    @PostMapping("/sendCode")
    public AppResponse<Object> sendCode(String phoneNo) {

        //1. 生成随机验证码保存到redis中,准备与用户提交的验证码进行比较
        String code = UUID.randomUUID().toString().substring(0, 4);
        //2. 保存验证码和电话号码对应关系,设置验证时间
        redisTemplate.opsForValue().set(phoneNo, code, 10000, TimeUnit.MINUTES);
        //3. 短信发送构造参数
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phoneNo);
        querys.put("param", "code:" + code);
        querys.put("tpl_id", "TP1711063"); //短信模板
        //4. 发送短信
        String sendCode = smsTemplate.sendCode(querys);

        if (sendCode.equals("") || sendCode.equals("fail")) {
            //短信失败
            return AppResponse.fail("短信发送失败");
        }
        return AppResponse.ok("短信发型成功");
    }


}
